package org.sith.taskrunner.servlets;

import org.sith.taskrunner.api.exceptions.TaskExecutionException;
import org.sith.taskrunner.api.exceptions.TaskInitException;
import org.sith.taskrunner.temp.tasks.quadraticequation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

public class QuadraticEquationServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out;
		String acceptEncoding = request.getHeader("accept-encoding");
		if((acceptEncoding!=null)&&(acceptEncoding.indexOf("gzip")!=-1)){
			out = new PrintWriter(new GZIPOutputStream(response.getOutputStream()), false);
			response.setHeader("content-encoding", "gzip");
		}else{
			out = response.getWriter();
		}
		try {
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Quadratic Equation</title>");
			out.println("</head>");
			out.println("<body bgcolor=#aabbff> ");
			out.println("<div align=center>");
			out.println("<form method=GET>");
			out.println("Equation");
			out.println("<input type=text name=a size=3>x<sup>2</sup> +");
			out.println("<input type=text name=b size=3>x +");
			out.println("<input type=text name=c size=3>= 0<p>");
			out.println("<input type=submit value=Solve>");
			out.println("</form><p>");
			makeEquation(out, request);
			out.println("</div>");
			out.println("</body>");
			out.println("</html>");
		} finally {
			out.close();
		}
	}
	
	public static void makeEquation(PrintWriter out, HttpServletRequest request){
		Triple triple = null;
		try{
			triple = new Triple(
					Double.parseDouble(request.getParameter("a")),
					Double.parseDouble(request.getParameter("b")),
					Double.parseDouble(request.getParameter("c")));
		}catch(NumberFormatException e){
			printError(out, e);
		}
		try{
			QuadraticEquationTask task = new QuadraticEquationTask();
			task.init(new QuadraticEquationInputData(triple));
			QuadraticEquationResult result = task.executeTask();
			Pair pairResult = result.getResult();
			out.println("Results x<sub>1</sub> = "+pairResult.getA()+", x<sub>2</sub> = "+pairResult.getB());
		}catch(TaskInitException e){
			printError(out, e);
		}catch(TaskExecutionException e){
			printError(out, e);
		}
	}
	 private static void printError(PrintWriter out, Exception e) {
	        out.println("<p style=\"color:red\">" + e.getLocalizedMessage() + "<p>");
	    }
}
